using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using System.Data;
using Prodma.DataAccess.Database;
using Prodma.DataAccess.Models.ViewModels;
using Prodma.DataAccess.DataService;
using Prodma.DataAccess.DataService.ListService;
using Prodma.DataAccess.Helper.Enumerators;
using Prodma.DataAccess.Authorization;
using Prodma.DataAccess.Repositories;
using System.Configuration;
using System.IO;

namespace Prodma.Panel.Controllers
{
    [Authorize]
    public class ArchiveController : Controller
    {
        
        #region Repository Setters

        private IArchiveRepository repository;

        public ArchiveController() : this(new ArchiveService()) { }

        public ArchiveController(IArchiveRepository _repository)
        {
            repository = _repository;
        }

        #endregion


        #region Index
        [NavigationFilter(MenuAdmins.ArchiveManagement, AuthorizationType.Read)]
        public ActionResult Index()
        {
            ViewData["projectList"] = repository.GetProjectList();
            ViewData["totalRowCount"] = repository.GetTotalRowCount();
            ViewData["archiveCounts"] = repository.GetCounts();

            if (Request.QueryString["find"] != "" && Request.QueryString["find"] != null)
            {
                Dictionary<string, string> find = new Dictionary<string, string>();
                find.Add("name", Request.QueryString["find"]);
                return View(repository.GetList(find));
            }
            else
            {
                return View(repository.GetList());
            }
        }
        #endregion


        #region New
        [NavigationFilter(MenuAdmins.ArchiveManagement, AuthorizationType.Write)]
        public ActionResult New()
        {
            ViewData["projectList"] = ProjectList.GetList();
            ViewData["stateList"] = StateList.GetList(StateType.General);

            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [NavigationFilter(MenuAdmins.ArchiveManagement, AuthorizationType.Write)]
        public ActionResult New(FormCollection form)
        {
            ViewData["projectList"] = ProjectList.GetList();
            ViewData["stateList"] = StateList.GetList(StateType.General);

            tb_Archive archive = new tb_Archive();
            archive.Name = Request.Form["name"];
            archive.Title = Request.Form["title"];
            archive.Folder = Request.Form["folder"];
            if (Request.Form["isLive"] == "false")
            {
                archive.IsLive = false;
            }
            else
            {
                archive.IsLive = true;
            }
            archive.tb_ProjectReference.EntityKey = new EntityKey("DataContext.tb_Project", "Id", Convert.ToInt32(Request.Form["ddlProject"]));
            archive.tb_StateReference.EntityKey = new EntityKey("DataContext.tb_State", "Id", Convert.ToInt32(Request.Form["ddlState"]));

            repository.New(archive);

            #region Create Folder

            string defaultImagePath = ConfigurationManager.AppSettings["contentImagePath"];
            string defaultFilePath = ConfigurationManager.AppSettings["contentFilePath"];

            Directory.CreateDirectory(Server.MapPath(defaultImagePath) + archive.Folder);
            Directory.CreateDirectory(Server.MapPath(defaultFilePath) + archive.Folder);

            #endregion

            return View();
        }
        #endregion


        #region Edit
        [NavigationFilter(MenuAdmins.ArchiveManagement, AuthorizationType.Update)]
        public ActionResult Edit()
        {
            int id = Convert.ToInt32(Request.QueryString["id"]);
            ArchiveVm archive = repository.Edit(id);

            ViewData["projectList"] = ProjectList.GetList(archive.Project.Id);
            ViewData["stateList"] = StateList.GetList(StateType.General, archive.State.Id);

            return View(archive);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [NavigationFilter(MenuAdmins.ArchiveManagement, AuthorizationType.Update)]
        public ActionResult Edit(FormCollection form)
        {
            tb_Archive archive = new tb_Archive();
            archive.Name = Request.Form["name"];
            archive.Title = Request.Form["title"];
            archive.Folder = Request.Form["folder"];
            if (Request.Form["isLive"] == "false")
            {
                archive.IsLive = false;
            }
            else
            {
                archive.IsLive = true;
            }
            archive.tb_ProjectReference.EntityKey = new EntityKey("DataContext.tb_Project", "Id", Convert.ToInt32(Request.Form["ddlProject"]));
            archive.tb_StateReference.EntityKey = new EntityKey("DataContext.tb_State", "Id", Convert.ToInt32(Request.Form["ddlState"]));

            int id = Convert.ToInt32(Request.Form["id"]);
            repository.Update(id, archive);

            #region Update Folder

            string defaultImagePath = ConfigurationManager.AppSettings["contentImagePath"];
            string defaultFilePath = ConfigurationManager.AppSettings["contentFilePath"];
            string currentFolder = Server.MapPath(defaultImagePath) + Request.Form["hdnFolder"];
            string destinationImageFolder = Server.MapPath(defaultImagePath) + archive.Folder;
            string destinationFileFolder = Server.MapPath(defaultFilePath) + archive.Folder;

            if (!Directory.Exists(destinationImageFolder) || !Directory.Exists(destinationFileFolder))
            {
                Directory.CreateDirectory(destinationImageFolder);
                Directory.CreateDirectory(destinationFileFolder);
            }
            else
            {
                if (currentFolder != destinationImageFolder)
                {
                    Directory.Move(currentFolder, destinationImageFolder);
                    Directory.Move(currentFolder, destinationFileFolder);
                }
            }

            #endregion

            return RedirectToAction("edit/?id=" + id);
        }
        #endregion


        #region Delete
        [NavigationFilter(MenuAdmins.ArchiveManagement, AuthorizationType.Delete)]
        public ActionResult Delete()
        {
            string[] idList = Request.QueryString["idList"].Split(',');

            foreach (string id in idList)
            {
                string deleteId = id.Substring(3, id.Length - 3);
                repository.Delete(Convert.ToInt32(deleteId));
            }

            return RedirectToAction("index");
        }
        #endregion


        #region Set Active && Passive
        [NavigationFilter(MenuAdmins.ArchiveManagement, AuthorizationType.Update)]
        public ActionResult SetActive()
        {
            string[] idList = Request.QueryString["idList"].Split(',');

            foreach (string id in idList)
            {
                string currentId = id.Substring(3, id.Length - 3);
                repository.SetActive(Convert.ToInt32(currentId));
            }

            return RedirectToAction("index");
        }
        [NavigationFilter(MenuAdmins.ArchiveManagement, AuthorizationType.Update)]
        public ActionResult SetPassive()
        {
            string[] idList = Request.QueryString["idList"].Split(',');

            foreach (string id in idList)
            {
                string currentId = id.Substring(3, id.Length - 3);
                repository.SetPassive(Convert.ToInt32(currentId));
            }

            return RedirectToAction("index");
        }
        #endregion

        
        #region Order Operation

        public ActionResult OrderUp()
        {
            int archiveId = Convert.ToInt32(Request.QueryString["id"]);
            int orderNo = Convert.ToInt32(Request.QueryString["orderNo"]);
            int project = Convert.ToInt32(Request.QueryString["project"]);

            ArchiveOrderVm archiveOrder = new ArchiveOrderVm();
            archiveOrder.Archive = archiveId;
            archiveOrder.OrderNo = orderNo;
            archiveOrder.Project = project;

            repository.OrderUp(archiveId, archiveOrder);

            return RedirectToAction("index");
        }

        public ActionResult OrderDown()
        {
            int archiveId = Convert.ToInt32(Request.QueryString["id"]);
            int orderNo = Convert.ToInt32(Request.QueryString["orderNo"]);
            int project = Convert.ToInt32(Request.QueryString["project"]);

            ArchiveOrderVm archiveOrder = new ArchiveOrderVm();
            archiveOrder.Archive = archiveId;
            archiveOrder.OrderNo = orderNo;
            archiveOrder.Project = project;

            repository.OrderDown(archiveId, archiveOrder);

            return RedirectToAction("index");
        }

        public ActionResult SetOrder()
        {
            int archiveId = Convert.ToInt32(Request.QueryString["id"]);
            int orderNo = Convert.ToInt32(Request.QueryString["orderNo"]);
            int project = Convert.ToInt32(Request.QueryString["project"]);
            int setOrderNo = Convert.ToInt32(Request.QueryString["setOrderNo"]);

            if (setOrderNo < 0)
            {
                return RedirectToAction("/index/?project=" + Request.QueryString["project"]);
            }

            ArchiveOrderVm archiveOrder = new ArchiveOrderVm();
            archiveOrder.Archive = archiveId;
            archiveOrder.OrderNo = orderNo;
            archiveOrder.Project = project;
            archiveOrder.SetOrderNo = setOrderNo;

            repository.SetOrder(archiveId, archiveOrder);

            return RedirectToAction("index");
        }
        #endregion

    }
}
